package com.uw.tookit;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class ServerCommunicator {
	// The URI to our server location.
	public static String URI = "http://ec2-23-21-229-182.compute-1.amazonaws.com/";
	
	/**
	 * @param serverFileName: the file on server to be called
	 * @param paramValues: a mapping of parameter names to its corresponding values to be passed to the server
	 *                     pass null if no parameters to be added.
	 * @return: a string representation of the results returned by the server
	 * 			null if not connected to the internet
	 */
	public static String executeHttpRequest(String serverFileName, Map<String, String> paramValues) {
		String result = "";
        InputStream is = null;

        //http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String url = URI + serverFileName;
            // Add paramters to the URL if provided.
            if (paramValues != null) {
            	url = addParamsToURL(url, paramValues);
            }
            HttpPost httppost = new HttpPost(url);
            
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            return null;
        }

        //convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
               sb.append(line + "\n");
            }
            is.close();

            result=sb.toString();
        } catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }
        return result;
	}

	/**
	 * @param url: The URL to which parameters values are appended.
	 * @param paramValues: a mapping of parameter to its values.
	 * @return: the new URL with the parameter values appended.
	 */
	private static String addParamsToURL(String url,Map <String, String> paramValues) {
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("year","1990"));
        for (String name: paramValues.keySet()) {
        	params.add(new BasicNameValuePair(name, paramValues.get(name)));
        }
		String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
		return url;
	}
}
